<?php
/*****************************************************************************
**	Класс:	Работа с пользователем											**
**	Автор:	Dark Dayver														**
**	Версия:	1.0b															**
**	Дата:	25/12-2009														**
*****************************************************************************/
if (IN_P_ENIGMA)
{
	die('HACK!');
}

class user
{
	var $id = false; // ID Пользователя
	private $db; // Ссылка на класс работы с БД
	private $config; // Ссылка на класс общих функций
	var $data = false; // Данные пользователя
	var $alliance = false; // Данные альянса пользователя
	var $faction = false; // Данные по фракции пользователя
	var $permission = false; // Данные по правам доступа пользователя

	function user($id = false)
	{
		global $db, $work;
		$this->db = $db;
		$this->config = $work->config;
		if (SERVER_NO)
		{
			if ($id === false)
			{
				if (isset($_SESSION['id']) && $_SESSION['id'] != 0) $id = $_SESSION['id'];
			}
			if ($id)
			{
				$this->db->select(array('activate', 'banned'), DB_USER, TBL_USERS);
				$this->db->where('`id` = ' . $id);
				$this->db->query();
				$tmp = $this->db->res_row();
				$this->db->clean();
				if ($tmp)
				{
					if ($tmp['banned'])
					{
						$tmp['banned'] = $this->banned_check($id);
					}
					$this->id = $id;
				}
			}
		}

		if ($this->id)
		{
			$this->get_data_of_user();
		}
		else
		{
			$this->clean_data_of_user();
		}
	}

	function get_data_of_user()
	{
		$this->db->select('*', DB_USER, TBL_USERS);
		$this->db->where('`id` = ' . $this->id);
		$this->db->query();
		$this->data = $this->db->res_row();
		$this->db->clean();
		if ($this->data)
		{
			unset($this->data['pass']);
			$this->db->select('*', DB_WORK, TBL_FACTION);
			$this->db->where('`id` = ' . $this->data['faction']);
			$this->db->query();
			$this->faction = $this->db->res_row();
			$this->db->clean();
			if ($this->faction)
			{
				$this->data['faction_name'] = $this->faction['name'];
				$this->db->select('*', DB_USER, TBL_ALLIANCE_USER);
				$this->db->where('`id_user` = ' . $this->id);
				$this->db->query();
				$this->alliance = $this->db->res_row();
				$this->db->clean();
				if ($this->alliance)
				{
					$this->data['alliance'] = $this->alliance['id_alliance'];
					$this->db->select('*', DB_USER, TBL_ALLIANCE);
					$this->db->where('`id` = ' . $this->alliance['id_alliance']);
					$this->db->query();
					$this->alliance = array_merge($this->alliance, $this->db->res_row());
					$this->db->clean();
					unset($this->alliance['id_alliance'], $this->alliance['id_user']);
				}
				else
				{
					$this->data['alliance'] = false;
				}
				$this->db->select('*', DB_USER, TBL_GROUP);
				$this->db->where('`id` = ' . $this->data['group']);
				$this->db->query();
				$this->permission = $this->db->res_row();
				$this->db->clean();
				if ($this->permission)
				{
					$this->data['group_name'] = $this->permission['name'];
					$this->data['group_description'] = $this->permission['description'];
					unset($this->permission['id'], $this->permission['name'], $this->permission['description']);
				}
				$this->db->select('*', DB_USER, TBL_PERMISSION);
				$this->db->where('`id` = ' . $this->id);
				$this->db->query();
				$tmp = $this->db->res_row();
				$this->db->clean();
				if ($tmp)
				{
					unset($tmp['id']);
					foreach ($tmp as $key=>$value)
					{
						if (isset($this->permission[$key])) $this->permission[$key] = $this->permission[$key] OR $value;
						else $this->permission[$key] = $value;

					}
				}
				$this->data['avatar'] = $this->get_avatar();
				if (empty($this->data['date_format'])) $this->data['date_format'] = $this->config['date_format'];
			}
			else
			{
				$this->clean_data_of_user();
			}
		}
		else
		{
			$this->clean_data_of_user();
		}
	}

	function clean_data_of_user()
	{
		if ($this->id === $_SESSION['id']) unset($_SESSION['id']);
		$this->id = false;
		$this->data = array();
		$this->alliance = array();
		$this->faction = array();
		$this->permission = array();
		$this->data['language'] = $this->config['language_def'];
		$this->data['theme'] = $this->config['theme_def'];
		$this->data['faction'] = false;
		$this->db->select('*', DB_USER, TBL_GROUP);
		$this->db->where('`id` = ' . $this->config['group_guest']);
		$this->db->query();
		$this->permission = $this->db->res_row();
		$this->db->clean();
		if ($this->permission)
		{
			$this->data['name'] = $this->permission['name'];
			unset($this->permission['id'], $this->permission['name'], $this->permission['description']);
		}
	}

	function last_active()
	{
		if ($this->id)
		{
			$active['date_last_active'] = date('Y-m-d H:i:s'); //YYYY-MM-DD HH:MM:SS
			$active['where_last_active'] = $_SERVER['QUERY_STRING'];
			$active['last_ip'] = $_SERVER['REMOTE_ADDR'];
			$this->db->update($active, DB_USER, TBL_USERS);
			$this->db->where('`id` = ' . $this->id);
			$this->db->query();
			$this->db->clean();
		}
	}

	function login_user($login, $password)
	{
		$this->db->select('id', DB_USER, TBL_USERS);
		$this->db->where('`login` = "' . $login . '" AND `pass` = "' . md5(sha1($login . $password)) . '"');
		$this->db->query();
		$tmp = $this->db->res_row();
		$this->db->clean();
		if ($tmp)
		{
			$this->id = $tmp['id'];
			$this->get_data_of_user();
		}
		else
		{
			$this->clean_data_of_user();
		}
	}

	function banned_check($id)
	{
		$tmp = true;
		$this->db->select(array('date_ban', 'term_ban'), DB_USER, TBL_USERS);
		$this->db->where('`id` = ' . $id);
		$this->db->query();
		$tmp = $this->db->res_row();
		$this->db->clean();
		if ($tmp)
		{
			if ((strtotime($tmp['date_ban']) + $tmp['term_ban']) <= time())
			{
				$this->db->update(array('banned' => 0), DB_USER, TBL_USERS);
				$this->db->where('`id` = ' . $id);
				$this->db->query();
				$this->db->clean();
				$tmp = false;
			}
		}
		return $tmp;
	}

	function ban_reason($id)
	{
		$tmp = false;
		$this->db->select(array('name', 'date_ban', 'term_ban', 'reason_ban'), DB_USER, TBL_USERS);
		$this->db->where('`id` = ' . $id);
		$this->db->query();
		$tmp = $this->db->res_row();
		$this->db->clean();
		if ($tmp)
		{
			$tmp['term_ban'] = date('Y-m-d H:i:s', (strtotime($tmp['date_ban']) + $tmp['term_ban']));
		}
		return $tmp;
	}

	function check_allow_login()
	{
		global $language;
		if ($this->id)
		{
			if ($this->data['banned'])
			{
				$this->data['banned'] = $this->banned_check($this->id);
			}
			if (!$this->data['activate'])
			{
				if (!$this->config['requires_activation'])
				{
					$this->db->update(array('activated_code' => NULL, 'activate' => '1'), DB_USER, TBL_USERS);
					$this->db->where('`id` = ' . $this->id);
					$this->db->query();
					if ($this->db->aff_rows)
					{
						$this->data['activate'] = true;
					}
					$this->db->clean();
				}
			}
			if (!$this->data['activate'])
			{
				$url_activated = $this->config['site_url'] . '?action=activate&amp;login=' . $this->data['login'] . '&amp;email=' . $this->data['email'];
				$url_resend = $this->config['site_url'] . '?action=activate&amp;login=' . $this->data['login'] . '&amp;email=' . $this->data['email'] . '&amp;resend=true';
				$this->clean_data_of_user();
				$_SESSION['error'] = true;
				$_SESSION['error_txt'] = $language->error['user_no_activated'] . sprintf('<br /><br /><div align="center"><a href="%s" title="%s"><b>%s</b></a><div>', $url_activated, $language->main['go_activate'], $language->main['go_activate']) . sprintf('<br /><br /><div align="center"><a href="%s" title="%s"><b>%s</b></a><div>', $url_resend, $language->main['resend_activate'], $language->main['resend_activate']);
			}
			else if ($this->data['banned'])
			{
				$banned = $this->ban_reason($this->id);
				$this->clean_data_of_user();
				$_SESSION['error'] = true;
				if ($banned)
				{
					$_SESSION['error_txt'] = sprintf($language->error['user_banned'], $banned['name'], $language->local_time($this->data['date_format'], $banned['date_ban']), $language->local_time($this->data['date_format'], $banned['term_ban']), $banned['reason_ban']);
				}
			}
			else if (!$this->config['allow_login'])
			{
				if (!isset($this->data['always_login']) || empty($this->data['always_login']) || $this->data['always_login'] == false)
				{
					$this->clean_data_of_user();
					$_SESSION['error'] = true;
					$_SESSION['error_txt'] = $language->error['server_not_login'];
				}
			}
		}
	}

	function gen_activated_code($id)
	{
		$code = false;
		if ($id)
		{
			$activated_code = md5(uniqid(rand()));
			$this->db->update(array('activate' => '0', 'activated_code' => $activated_code, 'date_regist' => date('Y-m-d H:i:s')), DB_USER, TBL_USERS);
			$this->db->where('`id` = ' . $id);
			$this->db->query();
			if ($this->db->aff_rows)
			{
				$code = $activated_code;
			}
			$this->db->clean();
		}
		return $code;
	}

	function activated_user($login, $email, $activated_code)
	{
		global $language;
		$result = false;
		$this->db->select(array('id', 'name', 'activated_code'), DB_USER, TBL_USERS);
		$this->db->where('`login` = "' . $login . '" AND `email` = "' . $email . '"');
		$this->db->query();
		$result = $this->db->res_row();
		$this->db->clean();
		if ($result)
		{
			if ($result['activated_code'] == $activated_code)
			{
				$this->db->update(array('activated_code' => NULL, 'activate' => '1'), DB_USER, TBL_USERS);
				$this->db->where('`id` = ' . $result['id']);
				$this->db->query();
				if ($this->db->aff_rows)
				{
					$_SESSION['info'] = true;
					$_SESSION['info_txt'] = sprintf($language->main['activated_user'], $result['name'], $email);
				}
				else
				{
					$result = false;
					$_SESSION['error'] = true;
					$_SESSION['error_txt'] = $language->error['unknown'];
				}
				$this->db->clean();
			}
			else
			{
				$_SESSION['error'] = true;
				$_SESSION['error_txt'] = sprintf($language->error['activated_code'], $result['name'], $email);
				$result = false;
			}
		}
		else
		{
			$_SESSION['error'] = true;
			$_SESSION['error_txt'] = $language->error['no_this_user'];
		}
		return $result;
	}

	function update_data($field, $value)
	{
		if ($this->id)
		{
			$this->db->update(array($field => $value), DB_USER, TBL_USERS);
			$this->db->where('`id` = ' . $this->id);
			$this->db->query();
			$tmp = $this->db->aff_rows;
			$this->db->clean();
			if ($tmp)
			{
				$this->data[$field] = $value;
				return true;
			}
		}
		return false;
	}

	function get_avatar($full = false)
	{
		global $work;

		$avatar_folder = $work->get_gallery_avatar((int)$this->data['gallery_avatar']);
		$this->db->select('avatar', DB_USER, TBL_USERS);
		$this->db->where('`id` = ' . $this->id);
		$this->db->query();
		$tmp = $this->db->res_row();
		$this->db->clean();
		$this->data['avatar'] = $tmp['avatar'];
		if ($full)
		{
			$avatar = array();
			if (!isset($this->data['avatar']) || empty($this->data['avatar']) || !file_exists($this->config['site_dir'] . 'avatar/' . $avatar_folder['folder'] . '/' . $this->data['avatar']))
			{
				$avatar['url'] = $this->config['site_url'] . 'avatar/' . $this->config['no_avatar_image'];
				$avatar['file'] = $this->config['site_dir'] . 'avatar/' . $this->config['no_avatar_image'];
				$avatar['name'] = $this->config['no_avatar_image'];
			}
			else
			{
				$avatar['url'] = $this->config['site_url'] . 'avatar/' . $avatar_folder['folder'] . '/' . $this->data['avatar'];
				$avatar['file'] = $this->config['site_dir'] . 'avatar/' . $avatar_folder['folder'] . '/' . $this->data['avatar'];
				$avatar['name'] = $this->data['avatar'];
			}
			$data_img = $this->get_data_img($avatar['file']);
			if ($data_img && $data_img['type'] != 'error')
			{
				$avatar['orig_width'] = $data_img['width'];
				$avatar['orig_height'] = $data_img['height'];
				$avatar['type'] = $data_img['type'];
				$tmp = $this->recalc_img_size($avatar['orig_width'], $avatar['orig_height'], $this->config['max_avatar_width'], $this->config['max_avatar_height']);
				$avatar['width'] = $tmp['width'];
				$avatar['height'] = $tmp['height'];
				return $avatar;
			}
			else
			{
				return false;
			}
		}
		else
		{
			if (!isset($this->data['avatar']) || empty($this->data['avatar']) || !file_exists($this->config['site_dir'] . 'avatar/' . $avatar_folder['folder'] . '/' . $this->data['avatar']))
			{
				return $this->config['site_url'] . 'avatar/' . $this->config['no_avatar_image'];
			}
			else
			{
				return $this->config['site_url'] . 'avatar/' . $avatar_folder['folder'] . '/' . $this->data['avatar'];
			}
		}
	}

	private function recalc_img_size($orig_width, $orig_height, $max_width, $max_height)
	{
		$result = array();
		if ($max_width == '0') $ratio_width = 1;
		else $ratio_width = $orig_width/$max_width;
		if ($max_height == '0') $ratio_height = 1;
		else $ratio_height = $orig_height/$max_height;
		if($orig_width < $max_width && $orig_height < $max_height && $max_width != '0' && $max_height != '0')
		{
			$result['width'] = $orig_width;
			$result['height'] = $orig_height;
		}
		else
		{
			if($ratio_width < $ratio_height)
			{
				$result['width'] = $orig_width/$ratio_height;
				$result['height'] = $orig_height/$ratio_height;
			}
			else
			{
				$result['width'] = $orig_width/$ratio_width;
				$result['height'] = $orig_height/$ratio_width;
			}
		}
		return $result;
	}

	private function get_data_img($file)
	{
		if (!file_exists($file)) return false;
		$data_img = getimagesize($file);
		$image['width'] = $data_img[0];
		$image['height'] = $data_img[1];
		switch ($data_img[2])
		{
			case 1:
				$image['type'] = 'gif';
				break;
			case 2:
				$image['type'] = 'jpg';
				break;
			case 3:
				$image['type'] = 'png';
				break;
			default:
				$image['type'] = 'error';
				break;
		}
		return $image;
	}

	function del_avatar()
	{
		if (strpos($this->data['avatar'], $this->config['no_avatar_image']) === false)
		{
			$tmp = $this->get_avatar(true);
			if ($this->update_data('avatar', NULL))
			{
				$this->update_data('gallery_avatar', '0');
				unlink($tmp['file']);
				$this->data['avatar'] = $this->get_avatar();
				return true;
			}
		}
		return false;
	}

	function upload_avatar($field)
	{
		global $work;

		if (!isset($_FILES[$field])) return false;
		else if ($_FILES[$field]['error'] == 4) return false;
		else if ($_FILES[$field]['size'] > $this->config['max_avatar_size']) return 'err_size';
		else
		{
			$tmp_data = $this->get_data_img($_FILES[$field]['tmp_name']);
			if ($tmp_data['type'] == 'error') return 'err_type';
			else
			{
				$tmp_data['orig_width'] = $tmp_data['width'];
				$tmp_data['orig_height'] = $tmp_data['height'];
				$tmp = $this->recalc_img_size($tmp_data['orig_width'], $tmp_data['orig_height'], $this->config['max_avatar_width'], $this->config['max_avatar_height']);
				$tmp_data['width'] = $tmp['width'];
				$tmp_data['height'] = $tmp['height'];
				$tmp_data['file'] = $_FILES[$field]['tmp_name'];
				if (!$this->resize_avatar($tmp_data))
				{
					return 'err_w_or_h';
				}
				$avatar_folder = $work->get_gallery_avatar(0);
				$avatar_folder = $this->config['site_dir'] . 'avatar/' . $avatar_folder['folder'] . '/';
				$avatar_name = md5(sha1(time() . $_FILES[$field]['name'])) . '.' . $tmp_data['type'];
				if (rename($_FILES[$field]['tmp_name'], $avatar_folder . $avatar_name))
				{
					$this->del_avatar();
					if ($this->update_data('avatar', $avatar_name)) return true;
					else
					{
						@unlink($avatar_folder . $avatar_name);
						return false;
					}
				}
				else return false;
			}
		}
	}

	private function resize_avatar(&$avatar)
	{
		if ($avatar['orig_width'] != $avatar['width'] || $avatar['orig_height'] != $avatar['height'])
		{
			switch($avatar['type'])
			{
				case 'gif':
					$imorig = imagecreatefromgif($avatar['file']);
					break;
				case 'jpg':
					$imorig = imagecreatefromjpeg($avatar['file']);
					break;
				case 'png':
					$imorig = imagecreatefrompng($avatar['file']);
					break;
				default:
					die ('HACK');
					break;
			}
			$im = imagecreatetruecolor($avatar['width'], $avatar['height']);
			if (imagecopyresampled($im, $imorig , 0, 0, 0, 0, $avatar['width'], $avatar['height'], $avatar['orig_width'], $avatar['orig_height']))
			{
				@unlink($avatar['file']);
				$avatar['type'] = 'png';
				imagepng($im, $avatar['file']);
				return true;
			}
			else return false;
		}
		else return true;
	}
}
?>
